import './index.scss';
import logo from '@/assets/logo.png';
import { Card, Form, Input, Button, Checkbox, message } from 'antd';
import { observer } from 'mobx-react-lite';
import useStore from '@/store';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

function Login() {
  const { loginStore } = useStore();
  const navigate = useNavigate();

  useEffect(() => {
    // 只有当本地有token的时候才去校验token，否则直接展示登录界面
    // const tokenCheck = async () => {
    //   if (loginStore.token) {
    //     try {
    //       const result = await loginStore.checkToken();
    //       if (result.isValid) {
    //         navigate('/Layout', { state: { username: result.username } });
    //       } else {
    //         message.error('token失效，请重新登录！');
    //       }
    //     } catch (e) {
    //       // console.log(e);
    //       message.error(e.message);
    //     }
    //   } else {
    //     console.log('本地没有token');
    //   }
    // };
    // tokenCheck();
  }, []);

  function onFinish(value) {
    const { username, password } = value;
    try {
      const log = async () => {
        const params = await loginStore.loginIn({ username, password });
        navigate('/Layout', { state: params });
      };
      log();
    } catch (e) {
      message.error(e.message);
    }
  }

  return (
    <div className="login">
      <Card hoverable className="login-container">
        <img className="login-img" src={logo} alt="logo" />
        <Form
          className="login-form"
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          validateTrigger={['onBlur', 'onChange']}
          autoComplete="off"
        >
          <Form.Item
            label="账号"
            name="username"
            rules={[
              { required: true, message: '请输入你的手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号',
                // validateTrigger: ['onBlur', 'onChange']
                validateTrigger: 'onBlur'
              }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入你的密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked">
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}

export default observer(Login);
// export default Login;
